package com.invoicerecognition.backend.service.impl.Invoice;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.invoicerecognition.backend.mapper.InvoiceMapper;
import com.invoicerecognition.backend.model.dto.Invoice;
import com.invoicerecognition.backend.model.dto.User;
import com.invoicerecognition.backend.service.Invoice.GetInvoiceRecordService;
import com.invoicerecognition.backend.service.impl.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GetInvoiceRecordServiceImpl implements GetInvoiceRecordService {

    @Autowired
    private InvoiceMapper invoiceMapper;

    @Override
    public JSONObject getRecord(int page) {
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        // 实现分页，IPage是mybatisplus的配置
        IPage<Invoice> recordIPage = new Page<>(page, 10);   // 第一个参数是第几页，第二个参数是每一页里面有多少个项目
        QueryWrapper<Invoice> queryWrapper =new QueryWrapper<>();
        queryWrapper.orderByDesc("id")
                .eq("user_id", user.getId());
        List<Invoice> records = invoiceMapper.selectPage(recordIPage, queryWrapper).getRecords();
        JSONObject resp = new JSONObject();
        resp.put("records", records);
        resp.put("records_count", invoiceMapper.selectCount(queryWrapper));

        return resp;
    }
}
